<template>
    <el-image-viewer v-if="viewerVisible" :url-list="HignSpeedUrls" :initial-index="imgcurrentIndex"
        @close="closeViewerimg" />
    <el-drawer v-model="isShow" size="50%" :destroy-on-close="true" @close="closeHandle" :close-on-press-escape="false"
        :close-on-click-modal="false" :show-close="false">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
        </template>
        <el-form :model="formDetail" ref="formDetailRef" :rules="rules" v-loading="loading" v-if="isshowformDetail">
            <el-row class="mb-3" :gutter="20">
                <el-col :span="12">
                    <el-form-item label="物品名称" label-width="80px" required prop="name">
                        <el-input v-model="formDetail.name" :readonly="isreadonly" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="物品数量" label-width="80px" required prop="num">
                        <el-input v-model="formDetail.num" @input="validateNumber" :readonly="isreadonly" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="处理方式" label-width="80px" required prop="treatment">
                        <el-input v-model="formDetail.treatment" type="textarea" resize="none" :rows="3"
                            :readonly="isreadonly" />
                    </el-form-item>
                </el-col>
                <el-col :span="24" style="font-size: 14px;">
                    <span style="color: red;">*&nbsp;提示：</span>&nbsp;&nbsp;
                    <span style="color: #666666;">物品信息填写后，请添加到列表中再点寄存！</span>
                </el-col>
            </el-row>
            <el-row class="mb-3" style="text-align:right" v-if="showAddBtnAll">
                <el-col :span="24">
                    <template v-if="isSeeformDetail">
                        <el-button type="primary" v-if="ishoswAddBtn" @click="AddList" class='mb-3'>
                            <el-icon class="me-2">
                                <Plus />
                            </el-icon>
                            添加到列表
                        </el-button>
                        <el-button type="primary" v-else @click="ConfirmEdit" class='mb-3'>
                            确认修改
                        </el-button>
                    </template>
                    <template v-else>
                        <el-button @click="closeSee" class='mb-3'>
                            取消查看
                        </el-button>
                    </template>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="GoodMainDetailList" show-overflow-tooltip class="mb-4" border>
            <el-table-column prop="name" label="物品名称" />
            <el-table-column prop="num" label="物品数量" />
            <el-table-column prop="treatment" label="处理方式" />
            <el-table-column fixed="right" label="操作" width="190px" align="center">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="EditMsg(scope.row, scope.$index)"
                        v-if="isAdd && form.state == 1">
                        <el-icon class="me-1">
                            <Edit />
                        </el-icon>
                        编辑
                    </el-button>
                    <el-button link type="primary" size="small" @click="SeeMsg(scope.row)">
                        <el-icon class="me-1">
                            <View />
                        </el-icon>
                        详情
                    </el-button>
                    <el-button link type="danger" size="small" v-if="isAdd && form.state == 1"
                        @click="remove(scope.row)">
                        <el-icon class="me-1">
                            <Delete />
                        </el-icon>
                        移除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-form :model="form" ref="formRef2" :rules="rules2" v-loading="loading">
            <el-row class="mb-3" :gutter="20">
                <template v-if="isshowget">
                    <el-col :span="12">
                        <el-form-item label="储物柜编号" label-width="100px">
                            <el-input v-model="form.lockersnum" :readonly="GetMsgisreadonly" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="储物柜密码" label-width="100px">
                            <el-input v-model="form.lockerspsw" type="password" show-password
                                :readonly="GetMsgisreadonly" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="寄存备注" label-width="100px">
                            <el-input v-model="form.remark" :readonly="GetMsgisreadonly" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="接收时间" label-width="100px" required prop="getdate">
                            <el-date-picker v-model="form.getdate" type="datetime" placeholder="请选择接收时间"
                                value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" :readonly="GetMsgisreadonly" />
                        </el-form-item>
                    </el-col>
                </template>
                <template v-if="isshowbackdata">
                    <el-col :span="12">
                        <el-form-item label="归还时间" label-width="100px" required prop="backdate">
                            <el-date-picker v-model="form.backdate" type="datetime" placeholder="请选择归还时间"
                                value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12"></el-col>
                </template>
                <template v-if="showgetGoodsdata">
                    <el-col :span="12" class="qianming">
                        <el-form-item label="涉案人签字-寄存" label-width="120px">
                            <div class="demo-image__error">
                                <el-image style="width: 110px; height: 110px" :src="SarSignUrlJC" fit="contain"
                                    :preview-src-list="srcListSarJC" :preview-teleported='true'>
                                    <template #error>
                                        <div class="image-slot">
                                            请签字
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <template v-if="isShowSignBtn">
                                <el-button type="primary" @click="SarSignBtn" v-if="SarSignUrlJC == ''"
                                    :disabled="isbackmsg">签字</el-button>
                                <el-button type="primary" @click="SarResignBtn" v-else
                                    :disabled="isbackmsg">重签</el-button>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="qianming">
                        <el-form-item label="承办人签字-寄存" label-width="120px">
                            <div class="demo-image__error">
                                <el-image style="width: 110px; height: 110px" :src="CBSignUrlJC" fit="contain"
                                    :preview-src-list="srcListCBJC" :preview-teleported='true'>
                                    <template #error>
                                        <div class="image-slot">
                                            请签字
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <template v-if="isShowSignBtn">
                                <el-button type="primary" @click="CBSignBtn" v-if="CBSignUrlJC == ''"
                                    :disabled="isbackmsg">签字</el-button>
                                <el-button type="primary" @click="CBResignBtn" v-else
                                    :disabled="isbackmsg">重签</el-button>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="qianming">
                        <el-form-item label="法警签字-寄存" label-width="120px">
                            <div class="demo-image__error">
                                <el-image style="width: 110px; height: 110px" :src="FJSignUrlJC" fit="contain"
                                    :preview-src-list="srcListFJJC" :preview-teleported='true'>
                                    <template #error>
                                        <div class="image-slot">
                                            请签字
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <template v-if="isShowSignBtn">
                                <el-button type="primary" @click="FJSignBtn" v-if="FJSignUrlJC == ''"
                                    :disabled="isbackmsg">签字</el-button>
                                <el-button type="primary" @click="FJResignBtn" v-else
                                    :disabled="isbackmsg">重签</el-button>
                            </template>
                        </el-form-item>
                    </el-col>
                </template>
                <template v-if="showbackGoodsdata">
                    <el-col :span="12" class="qianming">
                        <el-form-item label="涉案人签字-归还" label-width="120px">
                            <div class="demo-image__error">
                                <el-image style="width: 110px; height: 110px" :src="SarSignUrlGH" fit="contain"
                                    :preview-src-list="srcListSarGH" :preview-teleported='true'>
                                    <template #error>
                                        <div class="image-slot">
                                            请签字
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <template v-if="isShowSignBtn">
                                <el-button type="primary" @click="SarSignBtn" v-if="SarSignUrlGH == ''"
                                    :disabled="isbackmsg">签字</el-button>
                                <el-button type="primary" @click="SarResignBtn" v-else
                                    :disabled="isbackmsg">重签</el-button>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="qianming">
                        <el-form-item label="承办人签字-归还" label-width="120px">
                            <div class="demo-image__error">
                                <el-image style="width: 110px; height: 110px" :src="CBSignUrlGH" fit="contain"
                                    :preview-src-list="srcListCBGH" :preview-teleported='true'>
                                    <template #error>
                                        <div class="image-slot">
                                            请签字
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <template v-if="isShowSignBtn">
                                <el-button type="primary" @click="CBSignBtn" v-if="CBSignUrlGH == ''"
                                    :disabled="isbackmsg">签字</el-button>
                                <el-button type="primary" @click="CBResignBtn" v-else
                                    :disabled="isbackmsg">重签</el-button>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="qianming">
                        <el-form-item label="法警签字-归还" label-width="120px">
                            <div class="demo-image__error">
                                <el-image style="width: 110px; height: 110px" :src="FJSignUrlGH" fit="contain"
                                    :preview-src-list="srcListFJGH" :preview-teleported='true'>
                                    <template #error>
                                        <div class="image-slot">
                                            请签字
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <template v-if="isShowSignBtn">
                                <el-button type="primary" @click="FJSignBtn" v-if="FJSignUrlGH == ''"
                                    :disabled="isbackmsg">签字</el-button>
                                <el-button type="primary" @click="FJResignBtn" v-else
                                    :disabled="isbackmsg">重签</el-button>
                            </template>
                        </el-form-item>
                    </el-col>
                </template>
                <el-col :span="24" class="mt-2">
                    <el-row style="width: 100%;">
                        <el-col :span="10" >
                            <el-button v-if="isopenCameraBtn"  type="primary" @click="CameraBtn" class='mb-3'>
                                启动摄像头
                            </el-button>
                            <el-button v-else type="danger" @click="CloseCameraBtn" class='mb-3'>
                                关闭摄像头
                            </el-button>
                            <!-- <el-button   type="primary" @click="CameraBtn" class='mb-3'>
                                启动摄像头
                            </el-button>
                            <el-button  type="danger" @click="CloseCameraBtn" class='mb-3'>
                                关闭摄像头
                            </el-button> -->
                        </el-col>
                        <el-col :span="12">
                            <el-button v-if="!isopenCameraBtn" type="primary" @click="SaveCameraBtn" class='mb-3'>
                                拍照
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-row style="width: 100%;">
                    <el-col :span="22">
                        <div style="width: 422px;height: 302px;border: 1px solid #666666; background: #fff">
                            <canvas ref="videoCanvas" width="420" height="300"></canvas>
                        </div>
                    </el-col>
                </el-row>
                <el-col :span="24" style="display: flex;flex-wrap: wrap;">
                    <div class="block" style="width: 110px; height: 110px;position: relative;margin-right: 10px;"
                        v-for="(img, index) in HignSpeedUrls"  @click="clickImage(index)"
                        :key="index">
                        <el-image style="width: 110px; height: 110px;position: relative;"
                        :src="img"
                        fit="contain" 
                        >
                            <template #error>
                                <div class="image-slot">
                                    请使用高拍仪
                                </div>
                            </template>
                        </el-image>
                        <el-icon class="me-1 edit-icon" @click="deletHighSpeedImg(index, $event)">
                            <circle-close />
                        </el-icon>
                    </div>
                </el-col>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button type="primary" v-if="showgetGoodsBtn" @click="getGoods">寄存</el-button>
            <el-button type="primary" v-if="showbackGoodsBtn" @click="backGoods">归还</el-button>
            <el-button  @click="closeConfirm">关闭</el-button>
        </template>
    </el-drawer>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance()
import { GoodsMainAdd, GoodsMainEdit, GoodsMainInfo } from "@/api/ApplyDetail/ApplyDetail";
const { nj_sex, nj_sheanren_type, nj_sheanren_status } = proxy.useDict('nj_sex', 'nj_sheanren_type', 'nj_sheanren_status')

import { WebSocketService } from "@/utils/websocket";  // 导入 WebSocket 服务
import { getPoliceAreaInfo } from "@/api/PoliceAreaManage/PoliceAreaManage";
import { SignuploadFile, SignDelFile, SignList, SignimageInfo } from "@/api/ApplyDetail/ApplyDetail";


const isbackmsg = ref(false)
const isShow = ref(false)
const loading = ref(false)
const isreadonly = ref(false)
const ishoswAddBtn = ref(true)
const showAddBtnAll = ref(true)
const GetMsgisreadonly = ref(false)

const isshowget = ref(true)

const isshowformDetail = ref(true)
const isshowbackdata = ref(false)
const Backdataisreadonly = ref(false)
const showgetGoodsBtn = ref(true)
const showbackGoodsBtn = ref(false)
const showgetGoodsdata = ref(true)
const showbackGoodsdata = ref(false)

const viewerVisible = ref(false)
const imgcurrentIndex = ref(0);

const isopenCameraBtn = ref(true) // 摄像头按钮是否显示

// 新增帧率控制相关变量
const targetFPS = 20; // 目标帧率(可根据需要调整)1秒15帧。可以调整，越高越流畅，但是对内存及  Gpu要求越高
const frameInterval = 1000 / targetFPS; // 每帧间隔(ms)
let lastRenderTime = 0; // 上次渲染时间戳
let frameQueue = []; // 帧队列(最多保留1帧)
let isRendering = false; // 是否正在渲染中
let animationFrameId = null; // requestAnimationFrame ID


const videoCanvas = ref(null); // Canvas DOM 引用
const canvasCtx = ref(null);   // Canvas 2D 上下文

// 用于预览
const clickImage = (index) => {
    imgcurrentIndex.value = index
    setTimeout(() => {
        viewerVisible.value = true;
    }, 100);
};
// 用于关闭预览
const closeViewerimg = () => {
    viewerVisible.value = false;
}
const validateNumber = () => {
    // 只保留数字和空字符串  formDetail.num
    formDetail.value.num = formDetail.value.num.replace(/[^0-9]/g, '');
}
const isSeeformDetail = ref(true)

const isAdd = ref(true)

const currentIndex = ref(null); // 记录当前编辑的行索引
const user_name = ref('')

// 寄存
const isShowSignBtn = ref(true)
const isHighSpeedValue = ref()

const SarSignUrlJC = ref('')
const CBSignUrlJC = ref('')
const FJSignUrlJC = ref('')

const SarSignUrlJCID = ref()
const CBSignUrlJCID = ref()
const FJSignUrlJCID = ref()

const srcListSarJC = ref([])
const srcListCBJC = ref([])
const srcListFJJC = ref([])
// 、、、、
// 归还
const SarSignUrlGH = ref('')
const CBSignUrlGH = ref('')
const FJSignUrlGH = ref('')

const SarSignUrlGHID = ref()
const CBSignUrlGHID = ref()
const FJSignUrlGHID = ref()

const srcListSarGH = ref([])
const srcListCBGH = ref([])
const srcListFJGH = ref([])

const HignSpeedUrls = ref([])
const HignSpeedSubUploadID = ref([])

const SignType = ref()   //签字类型。5物品寄存涉案人签名6物品寄存承办人签名7物品寄存法警签名
// 8物品归还涉案人签名9物品归还承办人签名10物品归还法警签名
// WebSocket 服务实例
let webSocketService = null;
const websocketUrl = ref('')


const title = ref('物品寄存')
const form = ref({
    jwGoodsmainId: ''
})
const postData = ref({
    state: '1',
    jwGoodsmainId: ''
})
const formDetail = ref({})

const GoodMainDetailList = ref([])

const changeShowStatus = () => {
    isShow.value = !isShow.value
}
const rules = {
    name: [{ required: true, message: "物品名称不能为空", trigger: " " }],
    num: [{ required: true, message: "物品数量不能为空", trigger: " " }],
    treatment: [{ required: true, message: "处理方式不能为空", trigger: " " }],
}
const rules2 = {
    getdate: [{ required: true, message: "接收时间不能为空", trigger: "blur" }],
    backdate: [{ required: true, message: "归还时间不能为空", trigger: "blur" }],
}
// 通知事件
const emit = defineEmits(['getList'])
onMounted(() => {
    window.addEventListener('beforeunload', cleanup);
})
// 获取办案区ip地址
const getPoliceAreaInfos = async (querydata) => {
    const data = {
        unitId: querydata.policeAreaUnitId,
        areatype: querydata.TYPE
    }
    getPoliceAreaInfo(querydata.policearea_id).then(res => {
        console.log(111, 'istrue')
        websocketUrl.value = 'ws://' + res.data.ipAddress + ':' + res.data.port
        // 创建 WebSocket 实例
        webSocketService = new WebSocketService(websocketUrl.value);
        // webSocketService = new WebSocketService('ws://192.168.3.34:18887');
        // 启动 WebSocket 连接
        webSocketService.createWebSocket()
            .then(() => {
                const path = window.location.pathname
                const istrue =  path.includes('/PoliceWork/')
                console.log(istrue, 'istrue')
                // isAdd.value = false
                    if(istrue){
                        ElMessage.success({
                        message: '与终端设备连接成功',
                        showClose: true,
                    })
                }
            })
            .catch((error) => {
                proxy.$modal.msgError(`与终端连接失败`);
            });
        // 设置接收到消息时的回调
        webSocketService.setOnMessageCallback(handleWebSocketMessage);
    })
}
const jwApplydetailId = ref()
// 获取详情
const getInfo = async (jwGoodsmainId) => {
    console.log(jwGoodsmainId, 'jwGoodsmainId')
    await GoodsMainInfo(jwGoodsmainId).then(res => {
        form.value = res.data
        GoodMainDetailList.value = res.data.jwGoodsdetailList
    })
}
const showAdd = async (jwApplydetailId, data) => {
    console.log(jwApplydetailId, data, 'jwApplydetailId,data')
    changeShowStatus()
    setTimeout(() => {
        if (videoCanvas.value) {
            canvasCtx.value = videoCanvas.value.getContext('2d');
            videoCanvas.value.width = 420;
            videoCanvas.value.height = 300;
            console.log("Canvas初始化完成，尺寸:", videoCanvas.value.width, "x", videoCanvas.value.height);
        } else {
            console.error("Canvas元素未找到！");
        }
    }, 300);
    getPoliceAreaInfos(data)
    isAdd.value = true
    isbackmsg.value = false

    showgetGoodsdata.value = true
    showbackGoodsdata.value = false

    ishoswAddBtn.value = true
    isSeeformDetail.value = true
    isshowbackdata.value = false
    isshowget.value = true
    GetMsgisreadonly.value = false
    showgetGoodsBtn.value = true
    showbackGoodsBtn.value = false
    console.log("show新增", jwApplydetailId, data)
    // 这里应该是保存jwApplydetailId
    postData.value.jwApplydetailId = jwApplydetailId
    const querydata = {
        jwApplydetailId: data.jw_applydetail_id
    }
    GetImageDataJC(querydata)
    GetImageDataHighSpeed(querydata)
}
const GetImageDataHighSpeed = async (data) => {
    const HighSpeedSignQuery = { objectId: data.jwApplydetailId, type: 6 }
    //高拍仪
    SignList(HighSpeedSignQuery).then(res => {
        HignSpeedUrls.value = []
        HignSpeedSubUploadID.value = []
        for (var i = 0; i < res.data.length; i++) {
            HignSpeedSubUploadID.value[i] = res.data[i].jwUploadId
            const fileType = res.data[i].filename.split('.')[1]
            SignimageInfo(res.data[i].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                HignSpeedUrls.value.push(BlobUrlListData);
            })
        }
    })
}
const GetImageDataJC = async (data) => {
    const srcListSarJCQuery = { objectId: data.jwApplydetailId, type: 7 }
    const srcListCBJCQuery = { objectId: data.jwApplydetailId, type: 8 }
    const srcListFJJCQuery = { objectId: data.jwApplydetailId, type: 9 }

    //涉案人
    SignList(srcListSarJCQuery).then(res => {
        if (res.data.length > 0) {
            SarSignUrlJCID.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                SarSignUrlJC.value = BlobUrlListData
                srcListSarJC.value[0] = BlobUrlListData
            })
        }
    })
    //承办人
    SignList(srcListCBJCQuery).then(res => {
        if (res.data.length > 0) {
            CBSignUrlJCID.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                CBSignUrlJC.value = BlobUrlListData
                srcListCBJC.value[0] = BlobUrlListData
            })
        }
    })
    //法警
    SignList(srcListFJJCQuery).then(res => {
        if (res.data.length > 0) {
            FJSignUrlJCID.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                FJSignUrlJC.value = BlobUrlListData
                srcListFJJC.value[0] = BlobUrlListData
            })
        }
    })
}
const GetImageDataGH = async (data) => {
    const srcListSarGHQuery = { objectId: data.jwApplydetailId, type: 10 }
    const srcListCBGHQuery = { objectId: data.jwApplydetailId, type: 11 }
    const srcListFJGHQuery = { objectId: data.jwApplydetailId, type: 12 }

    //涉案人
    SignList(srcListSarGHQuery).then(res => {
        if (res.data.length > 0) {
            SarSignUrlGHID.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                SarSignUrlGH.value = BlobUrlListData
                srcListSarGH.value[0] = BlobUrlListData
            })
        }
    })
    //承办人
    SignList(srcListCBGHQuery).then(res => {
        if (res.data.length > 0) {
            CBSignUrlGHID.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                CBSignUrlGH.value = BlobUrlListData
                srcListCBGH.value[0] = BlobUrlListData
            })
        }
    })
    //法警
    SignList(srcListFJGHQuery).then(res => {
        if (res.data.length > 0) {
            FJSignUrlGHID.value = res.data[0].jwUploadId
            const fileType = res.data[0].filename.split('.')[1]
            SignimageInfo(res.data[0].jwUploadId).then(res => {
                const blob = new Blob([res], { type: 'image/' + fileType });
                const BlobUrlListData = URL.createObjectURL(blob);
                FJSignUrlGH.value = BlobUrlListData
                srcListFJGH.value[0] = BlobUrlListData
            })
        }
    })
}
const showEdit = async (data, isSee, username) => {
    postData.value.jwApplydetailId = data.jwApplydetailId
    isbackmsg.value = false
    changeShowStatus()
    setTimeout(() => {
        if (videoCanvas.value) {
            canvasCtx.value = videoCanvas.value.getContext('2d');
            videoCanvas.value.width = 420;
            videoCanvas.value.height = 300;
            console.log("Canvas初始化完成，尺寸:", videoCanvas.value.width, "x", videoCanvas.value.height);
        } else {
            console.error("Canvas元素未找到！");
        }
    }, 300);
    getPoliceAreaInfos(data)
    formDetail.value = { name: "", num: "", treatment: "" }; // 清空表单
    if (isSee == 'See') {
        title.value = '物品寄存归还'
        isreadonly.value = true

        showgetGoodsdata.value = false
        showbackGoodsdata.value = true

        Backdataisreadonly.value = false
        isshowformDetail.value = true
        showAddBtnAll.value = false
        isshowbackdata.value = true
        isshowget.value = true
        showgetGoodsBtn.value = false
        showbackGoodsBtn.value = true
        GetMsgisreadonly.value = true
        isSeeformDetail.value = true
        isAdd.value = false
        getInfo(data.jwGoodsmainId)
        GetImageDataGH(data)
        GetImageDataHighSpeed(data)

    }
    if (isSee == 'Edit') {
        title.value = '物品寄存编辑'

        showgetGoodsdata.value = true
        showbackGoodsdata.value = false

        isreadonly.value = false
        showAddBtnAll.value = true
        ishoswAddBtn.value = true
        isSeeformDetail.value = true
        isshowformDetail.value = true
        isshowbackdata.value = false
        isshowget.value = true
        showgetGoodsBtn.value = true
        GetMsgisreadonly.value = false
        showbackGoodsBtn.value = false

        isAdd.value = true
        getInfo(data.jwGoodsmainId)
        GetImageDataJC(data)
        GetImageDataHighSpeed(data)

    }
    if (isSee == 'LastSee') {
        title.value = '物品寄存详情'
        showgetGoodsdata.value = true
        showbackGoodsdata.value = true
        isShowSignBtn.value = false

        isreadonly.value = true
        showAddBtnAll.value = false
        ishoswAddBtn.value = true
        isSeeformDetail.value = true
        isshowformDetail.value = true
        isshowbackdata.value = true
        isshowget.value = true
        GetMsgisreadonly.value = true
        showgetGoodsBtn.value = false
        showbackGoodsBtn.value = false

        Backdataisreadonly.value = true
        isAdd.value = true
        getInfo(data.jwGoodsmainId)
        GetImageDataJC(data)
        GetImageDataGH(data)
        GetImageDataHighSpeed(data)
    }
}

const getGoods = () => {
    proxy.$refs["formRef2"].validate(valid => {
        if (valid) {
            if (GoodMainDetailList.value.length == 0 && (formDetail.value.name !== '' || formDetail.value.num !== '' || formDetail.value.treatment !== '')) {
                proxy.$modal.msgWarning(`检测到物品信息未添加到列表中，请先将物品信息填写完整并添加到列表中后再寄存`)
                return
            }
            if (form.value.jwGoodsmainId == '') {
                postData.value = { ...postData.value, ...form.value }
                postData.value.jwGoodsdetailList = GoodMainDetailList.value
            } else {
                postData.value = form.value
                postData.value.jwGoodsdetailList = GoodMainDetailList.value
            }
            postData.value.fileList = []
            if (HignSpeedSubUploadID.value.length > 0) {
                postData.value.fileList = HignSpeedSubUploadID.value
            }
            if (SarSignUrlJCID.value) {
                postData.value.fileList.push(SarSignUrlJCID.value);
            }
            if (CBSignUrlJCID.value) {
                postData.value.fileList.push(CBSignUrlJCID.value);
            }
            if (FJSignUrlJCID.value) {
                postData.value.fileList.push(FJSignUrlJCID.value);
            }
            console.log(postData.value)
            GoodsMainAdd(postData.value).then(res => {
                closewebSocketService()
                changeShowStatus()
                proxy.$modal.msgSuccess("寄存成功");
                emit('getList', '来了老弟')
            })
        }
    });
};

const backGoods = () => {
    proxy.$refs["formRef2"].validate(valid => {
        if (valid) {
            form.value.state = '2'
            postData.value.backFileList = []
            if (HignSpeedSubUploadID.value.length > 0) {
                postData.value.backFileList = HignSpeedSubUploadID.value
            }
            if (SarSignUrlJCID.value) {
                postData.value.backFileList.push(SarSignUrlJCID.value);
            }
            if (CBSignUrlJCID.value) {
                postData.value.backFileList.push(CBSignUrlJCID.value);
            }
            if (FJSignUrlJCID.value) {
                postData.value.backFileList.push(FJSignUrlJCID.value);
            }
            GoodsMainEdit(form.value).then(res => {
                closewebSocketService()
                changeShowStatus()
                proxy.$modal.msgSuccess("归还成功");
                emit('getList', '来了老弟')
            })
        }
    });
};
defineExpose({ showAdd, showEdit })

// 添加到列表
const AddList = () => {
    proxy.$refs["formDetailRef"].validate(valid => {
        if (valid) {
            GoodMainDetailList.value.push({ ...formDetail.value });
            formDetail.value = { name: "", num: "", treatment: "" }; // 清空表单
        }
    });
};
// 关闭查看详情
const closeSee = () => {
    formDetail.value = {}
    isSeeformDetail.value = true
    ishoswAddBtn.value = true
    isreadonly.value = false
};

// 编辑表格中的某一行
const EditMsg = (row, index) => {
    showAddBtnAll.value = true      //显示添加，确认修改-关闭按钮总
    isSeeformDetail.value = true    //显示上面的 录入操作
    ishoswAddBtn.value = false       //显示添加到列表按钮

    formDetail.value = { ...row }; // 深拷贝行数据到表单
    currentIndex.value = index; // 保存当前编辑的行索引
    isreadonly.value = false; // 使表单可编辑
};

// 详情-表格中的某一行
const SeeMsg = (row) => {
    if (showAddBtnAll) {
        ishoswAddBtn.value = false
        isSeeformDetail.value = false
        formDetail.value = { ...row }; // 深拷贝行数据到表单
        isreadonly.value = true; // 使表单可编辑
    } else {
        isSeeformDetail.value = true
        formDetail.value = { ...row }; // 深拷贝行数据到表单
        isreadonly.value = true; // 使表单可编辑
    }

};
// 确定按钮点击，更新表格中的数据
const ConfirmEdit = () => {
    if (currentIndex.value !== null) {
        GoodMainDetailList.value[currentIndex.value] = { ...formDetail.value }; // 更新表格中的数据
        formDetail.value = { name: "", num: "", treatment: "" }; // 清空表单
        currentIndex.value = null; // 重置索引
        isreadonly.value = false; // 确认后切回添加模式
        ishoswAddBtn.value = true
    }
};

const remove = (row) => {
    const index = GoodMainDetailList.value.indexOf(row);
    if (index !== -1) {
        // 使用 splice 删除指定索引处的元素
        GoodMainDetailList.value.splice(index, 1);
    }
}

// 物品-寄存-涉案人签名
const SarSignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
    }
    proxy.$modal.msg(`涉案人签字`)
    isbackmsg.value = true
    isHighSpeedValue.value = 1   //1签名，2高拍仪
    //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
    //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
    if (isAdd.value) {
        SignType.value = '7'
    } else {
        SignType.value = '10'
    }
    setTimeout(() => {
        websocket()
    }, 100);
}
// 物品-寄存-涉案人重新签字
const SarResignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
        
    }
    isbackmsg.value = true
    proxy.$modal.msg(`涉案人重新签字`)
    isHighSpeedValue.value = 1   //1签名，2高拍仪
    if (isAdd.value) {
        SignType.value = '7'   //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
        //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
        if (SarSignUrlJCID.value) {
            await SignDelFile(SarSignUrlJCID.value).then(res => {
                SarSignUrlJC.value = ''
            })
        }
    } else {
        SignType.value = '10'
        if (SarSignUrlGHID.value) {
            await SignDelFile(SarSignUrlGHID.value).then(res => {
                SarSignUrlGH.value = ''
            })
        }
    }
    setTimeout(() => {
        websocket()
    }, 100);
}
// 物品-寄存-承办人签字
const CBSignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
        
    }
    isbackmsg.value = true
    proxy.$modal.msg(`承办人签字`)
    isHighSpeedValue.value = 1   //1签名，2高拍仪
    if (isAdd.value) {
        SignType.value = '8'   //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
        //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
    } else {
        SignType.value = '11'
    }
    setTimeout(() => {
        websocket()
    }, 300);
}
// 物品-寄存-承办人重新签字
const CBResignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
        
    }
    isbackmsg.value = true
    proxy.$modal.msg(`承办人重新签字`)
    isHighSpeedValue.value = 1   //1签名，2高拍仪
    if (isAdd.value) {
        SignType.value = '8'   //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
        //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
        if (CBSignUrlJCID.value) {
            await SignDelFile(CBSignUrlJCID.value).then(res => {
                CBSignUrlJC.value = ''
                setTimeout(() => {
                    websocket()
                }, 300);
            })
        }
    } else {
        SignType.value = '11'
        if (CBSignUrlGHID.value) {
            await SignDelFile(CBSignUrlGHID.value).then(res => {
                CBSignUrlGH.value = ''
                setTimeout(() => {
                    websocket()
                }, 300);
            })
        }

    }

}
// 物品-寄存-法警签字
const FJSignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
        
    }
    isbackmsg.value = true
    proxy.$modal.msg(`法警签字`)
    isHighSpeedValue.value = 1   //1签名，2高拍仪
    if (isAdd.value) {
        SignType.value = '9'   //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
        //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
    } else {
        SignType.value = '12'
    }
    setTimeout(() => {
        websocket()
    }, 300);
}
// 物品-寄存-法警重新签字
const FJResignBtn = async () => {
    if(isHighSpeedValue.value == 2){
        CloseCameraBtn()
        
    }
    isbackmsg.value = true
    proxy.$modal.msg(`法警重新签字`)
    isHighSpeedValue.value = 1   //1签名，2高拍仪
    if (isAdd.value) {
        SignType.value = '9'   //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
        //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名

        if (FJSignUrlJCID.value) {
            await SignDelFile(FJSignUrlJCID.value).then(res => {
                FJSignUrlJC.value = ''
                setTimeout(() => {
                    websocket()
                }, 300);
            })
        }
    } else {
        SignType.value = '12'
        if (FJSignUrlGHID.value) {
            await SignDelFile(FJSignUrlGHID.value).then(res => {
                FJSignUrlGH.value = ''
                setTimeout(() => {
                    websocket()
                }, 300);
            })
        }
    }

}
// // 点击高拍仪
// const HighSpeedBtn = async () => {
//     isHighSpeedValue.value = 2
//     isbackmsg.value = true
//     proxy.$modal.msg(`正在启动高拍仪...`)
//     websocket()
// }
// 发送消息
function SendMes() {
    webSocketService.sendMessage(isHighSpeedValue.value)        //1是签名，2是高拍仪，3是身份证
}
// 点击启动摄像头
function CameraBtn() {
    isHighSpeedValue.value = 2
    if(webSocketService.ws.readyState == 1){
        webSocketService.sendMessage(2) //1是签名，2是高拍仪，3是身份证
        isopenCameraBtn.value = false // 摄像头按钮是否显示
    }else{
      // 创建 WebSocket 实例
      webSocketService = new WebSocketService(websocketUrl.value);
    //   webSocketService = new WebSocketService('ws://192.168.3.34:18887');
      // 启动 WebSocket 连接
      webSocketService.createWebSocket()
        .then(() => {
        //   ElMessage.success({
        //     message: '与终端设备连接成功',
        //     showClose: true,
        //   })
          // 设置接收到消息时的回调
          webSocketService.setOnMessageCallback(handleWebSocketMessage);
          // 发送消息
          webSocketService.sendMessage(2)
          isopenCameraBtn.value = false // 摄像头按钮是否显示
        })
        .catch((error) => {
          // proxy.$modal.error(`WebSocket 连接失败: ${error.message}`);
        });
    }
    
}
// 点击关闭摄像头{
  function CloseCameraBtn() {
    if(webSocketService){
        webSocketService.sendMessage('closeCamera')
        isopenCameraBtn.value = true // 摄像头按钮是否显示
        // 清空画布
        clearCanvas();
    }
   
}
// 清空画布的函数
function clearCanvas() {
  if (canvasCtx.value && videoCanvas.value) {
    console.log("清空画布")
    // 清除整个画布
    // 强制重绘（备用方案）
  setTimeout(() => {
    if (canvasCtx.value) {
      canvasCtx.value.clearRect(0, 0, 
        videoCanvas.value.width, 
        videoCanvas.value.height);
    }
    // 可选：填充白色背景（如果需要）
      canvasCtx.value.fillStyle = '#ffffff';
      canvasCtx.value.fillRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
  }, 500);
  }
}
// 点击保存图片
async function SaveCameraBtn() {
  webSocketService.sendMessage(11) // 1是签名，2是高拍仪，3是身份证
}
// webSocketService建立连接
const websocket = async () =>{
    console.log(webSocketService.ws.readyState)
        if(webSocketService.ws.readyState == 1){
            SendMes(isHighSpeedValue.value)
            isopenCameraBtn.value = false // 摄像头按钮是否显示
        }else{
             // 创建 WebSocket 实例
            // webSocketService = new WebSocketService('ws://192.168.3.34:18887');
            webSocketService = new WebSocketService(websocketUrl.value);
            // 启动 WebSocket 连接
            webSocketService.createWebSocket()
            .then(() => {
                const path = window.location.pathname
                const istrue =  path.includes('/PoliceWork/')
                if(istrue){
                //     ElMessage.success({
                //     message: '与终端设备连接成功-进入111',
                //     showClose: true,
                // })
                // 发送消息
                webSocketService.setOnMessageCallback(handleWebSocketMessage);
                SendMes(isHighSpeedValue.value)
                isopenCameraBtn.value = false // 摄像头按钮是否显示
                }
                
            })
            .catch((error) => {
                proxy.$modal.error(`WebSocket 连接失败: ${error.message}`);
            });
        }
}

// 处理 WebSocket 消息
function handleWebSocketMessage(message) {
    let imgUrl = ''
    isbackmsg.value = false
    if (message === 'cancel' || message === 'end') {
        proxy.$modal.msgWarning(`用户${message === 'cancel' ? '取消' : '结束'}了操作`);
        return;
    }

    if (isHighSpeedValue.value == '2') {    //message instanceof Blob
        // const query = {
        //     jwApplyDetailId: postData.value.jwApplydetailId,
        //     md5key: '12313',
        //     fileType: '6'                   //  3体检高拍仪 4体检医生签名 5体检涉案人签名
        // }
        if(typeof message === 'string'){
            try {
                    const data = JSON.parse(message);
                    if (data.photo) {
                        // 处理拍照结果...// 创建Base64图片URL
                    const imgUrl = `data:image/jpeg;base64,${data.photo}`;
                    // 将图片URL添加到HignSpeedUrls数组
                    HignSpeedUrls.value.push(imgUrl);
                    // 2. 转成 Blob（base64 => binary）
                    const byteString = atob(data.photo);
                    const arrayBuffer = new ArrayBuffer(byteString.length);
                    const uint8Array = new Uint8Array(arrayBuffer);
                    for (let i = 0; i < byteString.length; i++) {
                        uint8Array[i] = byteString.charCodeAt(i);
                    }
                    const blob = new Blob([uint8Array], { type: 'image/jpeg' });

                    // 3. 准备上传参数
                    const query = {
                        jwApplyDetailId: postData.value.jwApplydetailId,
                        md5key: '12313',
                        fileType: '6' //  3体检高拍仪 4体检医生签名 5体检涉案人签名
                    };

                    const formData = new FormData();
                    formData.append('file', blob, 'capture.jpg');

                    // 4. 调用上传接口
                    SignuploadFile(formData, query).then(res => {
                        proxy.$modal.msgSuccess(`照片上传成功`);
                        HignSpeedSubUploadID.value.push(res.msg);
                    });
                    }
                    return; // 拍照逻辑结束后直接返回
                } catch (e) {
                    console.warn("非JSON消息:", message);
                }
            }
            // 情况2：视频流的Blob数据
            if (message instanceof Blob) {
                if (frameQueue.length > 0) {
                    frameQueue[0] = message;
                } else {
                    frameQueue.push(message);
                }
                scheduleRender();
            }
    } else {
        imgUrl = message;
        if (SignType.value == '7') {
            SarSignUrlJC.value = imgUrl
            srcListSarJC.value[0] = imgUrl
            const query = {
                jwApplyDetailId: postData.value.jwApplydetailId,
                md5key: '12313',
                fileType: '7'            //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
                //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                SarSignUrlJCID.value = res.msg
            }).catch(error => {
                console.error('上传失败', error)
            });
        }
        if (SignType.value == '8') {
            CBSignUrlJC.value = imgUrl
            srcListCBJC.value[0] = imgUrl
            const query = {
                jwApplyDetailId: postData.value.jwApplydetailId,
                md5key: '12313',
                fileType: '8'            //  //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
                //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                CBSignUrlJCID.value = res.msg
            }).catch(error => {
                console.error('上传失败', error)
            });
        }
        if (SignType.value == '9') {
            FJSignUrlJC.value = imgUrl
            srcListFJJC.value[0] = imgUrl
            const query = {
                jwApplyDetailId: postData.value.jwApplydetailId,
                md5key: '12313',
                fileType: '9'            //  //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
                //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                FJSignUrlJCID.value = res.msg
            }).catch(error => {
                console.error('上传失败', error)
            });
        }

        if (SignType.value == '10') {
            SarSignUrlGH.value = imgUrl
            srcListSarGH.value[0] = imgUrl
            const query = {
                jwApplyDetailId: postData.value.jwApplydetailId,
                md5key: '12313',
                fileType: '10'            //  //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
                //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                SarSignUrlGHID.value = res.msg
            }).catch(error => {
                console.error('上传失败', error)
            });
        }
        if (SignType.value == '11') {
            CBSignUrlGH.value = imgUrl
            srcListCBGH.value[0] = imgUrl
            const query = {
                jwApplyDetailId: postData.value.jwApplydetailId,
                md5key: '12313',
                fileType: '11'            //  //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
                //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                CBSignUrlGHID.value = res.msg
            }).catch(error => {
                console.error('上传失败', error)
            });
        }
        if (SignType.value == '12') {
            FJSignUrlGH.value = imgUrl
            srcListFJGH.value[0] = imgUrl
            const query = {
                jwApplyDetailId: postData.value.jwApplydetailId,
                md5key: '12313',
                fileType: '12'            //  //6物品寄存高拍仪 7物品寄存涉案人签名 8物品寄存承办人签名 9物品寄存法警签名 
                //10物品归还涉案人签名 11物品归还承办人签名 12物品归还法警签名
            }
            uploadBase64Image(imgUrl, query).then(res => {
                proxy.$modal.msgSuccess(`上传成功`)
                FJSignUrlGHID.value = res.msg
            }).catch(error => {
                console.error('上传失败', error)
            });
        }
    }
}
// 删除图片
const deletHighSpeedImg = async (index, event) => {
    event.stopPropagation();
    await SignDelFile(HignSpeedSubUploadID.value[index]).then(res => {
        HignSpeedUrls.value.splice(index, 1);
        HignSpeedSubUploadID.value.splice(index, 1);
        proxy.$modal.msgSuccess(`删除成功`)
    })
}

// 关闭webSocketService
const closewebSocketService = () => {
  if(webSocketService){
    webSocketService.close()
  }
}
// defineExpose({closewebSocketService})
// 返回的base64数据进行处理-上传
function uploadBase64Image(base64Data, query) {
    // 1. 去掉 Base64 前缀部分（例如 'data:image/png;base64,'）
    const base64Str = base64Data.split(',')[1];

    // 2. 将 Base64 字符串转换为二进制数据
    const byteCharacters = atob(base64Str);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset++) {
        const byte = byteCharacters.charCodeAt(offset);
        byteArrays.push(byte);
    }
    // 3. 创建一个 Blob 对象，设置文件类型（如 image/png）
    const byteArray = new Uint8Array(byteArrays);
    const blob = new Blob([byteArray], { type: 'image/png' });
    // 4. 创建 FormData 对象
    const formData = new FormData();
    formData.append('file', blob, 'image.png');  // 这里的 'image.png' 是文件名，你可以根据需要修改
    // 6. 调用接口进行上传
    return SignuploadFile(formData, query);  // 这里传递 formData 和 query
}

// 新增的调度渲染函数
function scheduleRender() {
    // 如果已经在渲染或队列为空，则跳过
    if (isRendering || frameQueue.length === 0) return;
    
    const now = performance.now();
    const elapsed = now - lastRenderTime;
    
    // 如果还没到下一帧的渲染时间，延迟执行
    if (elapsed < frameInterval) {
        if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
        }
        animationFrameId = requestAnimationFrame(() => {
            scheduleRender();
        });
        return;
    }
    
    // 执行渲染
    processRender();
}

// 新增的处理渲染函数
function processRender() {
    if (isRendering || frameQueue.length === 0) return;
    
    isRendering = true;
    const blob = frameQueue.shift();
    lastRenderTime = performance.now();
    
    // 使用Blob创建对象URL
    const url = URL.createObjectURL(blob);
    const img = new Image();
    
    img.onload = () => {
        if (canvasCtx.value) {
            canvasCtx.value.clearRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
            canvasCtx.value.drawImage(
                img, 
                0, 0, 
                videoCanvas.value.width, 
                videoCanvas.value.height
            );
        }
        
        // 清理资源
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 检查是否有新帧需要处理
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    
    img.onerror = (e) => {
        console.error("图片加载失败:", e);
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 即使出错也继续处理下一帧
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    img.src = url;
}
// 统一的清理函数
const cleanup = () => {
  CloseCameraBtn();
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
    animationFrameId = null; // 重置为null
  }
  frameQueue = [];
  if (webSocketService) {
    // webSocketService.close();
    webSocketService = null; // 重置为null
  }
};
// 关闭后的回调事件
const closeHandle = () => {
    emit('getList', '来了来了')
}

const closeConfirm = () => {
    CloseCameraBtn();
    closewebSocketService()
    form.value = {}
    changeShowStatus()
}
// 组件卸载前的处理
onBeforeUnmount(() => {
  cleanup();
});

onUnmounted(() => {
  window.removeEventListener('beforeunload', cleanup);
});
</script>
<style>
.demo-image__error .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    display: inline-block;
    width: 49%;
    box-sizing: border-box;
    vertical-align: top;
}

.demo-image__error .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

.demo-image__error .el-image {
    max-width: 300px;
    max-height: 200px;
    width: 100%;
    height: 200px;
}

.demo-image__error .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 16px;
}

.demo-image__error .image-slot .el-icon {
    font-size: 16px;
}

.qianming .el-form-item__content {
    align-items: flex-start;
}

.el-image-viewer__canvas .el-image-viewer__img {
    background: white;
}
</style>